package com.feng.test.pdf;


import java.awt.image.BufferedImage;
import java.io.*;
import java.util.UUID;
import javax.imageio.ImageIO;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;


/**
 * @author HuangSuip
 */
public class PDF22Image {

    public static void main(String[] args) {
        pdfToImageToPdf("E:\\word\\004.pdf");
    }

    public static void pdfToImageToPdf(String s) {
        File file = new File(s);
        try {
            PDDocument doc = PDDocument.load(file);
            PDFRenderer renderer = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();

            for (int i = 0; i < pageCount; i++) {
                String filePath = "E:\\word\\" + UUID.randomUUID().toString().substring(0, 8);
                OutputStream os = new FileOutputStream(new File(filePath + ".jpg"));
                long t1 = System.currentTimeMillis();
                ByteArrayOutputStream bb = new ByteArrayOutputStream();
                BufferedImage image = renderer.renderImage(i, 1.5f);   //第二个参数越大生成图片分辨率越高。
                long t2 = System.currentTimeMillis();
                ImageIO.write(image, "jpg", os);
                long t3 = System.currentTimeMillis();
                //Image jpg = Image.getInstance(bb.toByteArray());
                long t4 = System.currentTimeMillis();
                //此处百分比与前面的分辨率参数相乘结果为1，则可保证等比输出。
                //jpg.scalePercent(80.0f);
                //jpg.setAlignment(Image.ALIGN_CENTER);
                long t5 = System.currentTimeMillis();
                System.out.println((t2 - t1) + "***" + (t3 - t2) + "***" + (t4 - t3) + "***" + (t5 - t4));
                os.close();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
